package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WXService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author zhmwi
 * @Date 2021/7/23
 * @Dersciption
 */
@RestController
@Api("对接微信支付")
@RequestMapping("/api/order/weixin/")
public class WXController {
    @Autowired
    private WXService wxService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OrderService orderService;
    //下单 生成微信二维码
    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable("orderId") Long orderId){
        Map map = wxService.createNative(orderId);
        return R.ok().data(map);
    }
    //查询支付状态
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(@PathVariable Long orderId){
        //调用接口查询交易结果
        Map<String,String> map = wxService.getPayStatus(orderId, PaymentTypeEnum.WEIXIN.getStatus());
        if (map == null){
            //支付失败 返回失败
            return R.error().message("支付失败");
        }
        //支付成功更新订单状态 更新交易记录
        if ("SUCCESS".equals(map.get("trade_state"))){
            //更改订单状态
            String out_trade_no = map.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,PaymentTypeEnum.WEIXIN.getStatus(),map);
            return R.ok().message("支付成功");
        }

        //返回支付中
        return R.ok().message("支付中");
    }

    @ApiOperation("取消预约")
    @GetMapping("auth/cancelOrder/{orderId}")
    public R cancelOrder(@PathVariable("orderId") Long orderId){
        Boolean flag = orderService.cancelOrder(orderId);
        return R.ok().data("flag",flag);
    }
}
